//
//  YSTitleView.m
//  YSPageViewExample_OC
//
//  Created by MOLBASE on 2017/12/5.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSTitleView.h"
#import "YSPageStyle.h"
#import "YSContentView.h"
#import "UIView+YSFrame.h"
#import "UIColor+YSExtension.h"

@interface YSDisplayTitleLabel : UILabel

@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) UIColor *fillColor;

@end

@interface YSTitleView () <YSContentViewDelegate>

@property (nonatomic, strong) NSArray<NSString *> *titleArray;
@property (nonatomic, strong) YSPageStyle *style;

@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, assign) CGFloat lastOffsetX;
@property (nonatomic, assign) BOOL isClickTitle;

@property (nonatomic, strong) UIScrollView *scrollView;
/// 标题Label数组
@property (nonatomic, strong) NSMutableArray *titleLabelArray;
/// Label宽度数组
@property (nonatomic, strong) NSMutableArray *titleSizeArray;

/// 分割线
@property (nonatomic, strong) UIView *separatorLine;
/// 下划线
@property (nonatomic, strong) UIView *underLine;

/// 遮罩
@property (nonatomic, strong) UIView *coverView;

/// 开始颜色,取值范围0~1
@property (nonatomic, assign) CGFloat startR;
@property (nonatomic, assign) CGFloat startG;
@property (nonatomic, assign) CGFloat startB;

/// 完成颜色,取值范围0~1
@property (nonatomic, assign) CGFloat endR;
@property (nonatomic, assign) CGFloat endG;
@property (nonatomic, assign) CGFloat endB;

@end

@implementation YSTitleView

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray<NSString *> *)titleArray style:(YSPageStyle *)style {
    if (self = [super initWithFrame:frame]) {
        self.titleArray = titleArray;
        self.style = style;
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.currentIndex = self.style.selectIndex;
    
    // 初始化颜色
    NSArray *nRGB = [self.style.titleNormalColor getRGBComponents];
    NSArray *sRGB = [self.style.titleSelectedColor getRGBComponents];
    _startR = [nRGB[0] floatValue];
    _startG = [nRGB[1] floatValue];
    _startB = [nRGB[2] floatValue];
    
    _endR = [sRGB[0] floatValue];
    _endG = [sRGB[1] floatValue];
    _endB = [sRGB[2] floatValue];
    
    // 1. 添加滚动View
    [self addSubview:self.scrollView];
    
    // 2. 添加遮罩
    if (self.style.isShowTitleCover) {
        [self.scrollView addSubview:self.coverView];
    }
    
    // 3. 添加title对应的Label
    [self setupTitleLabels];
    
    // 4. 添加分割线
    if (self.style.isHaveTitleSeparator) {
        [self addSubview:self.separatorLine];
    }
    
    // 5. 添加下划线
    if (self.style.isShowUnderLine) {
        [self.scrollView addSubview:self.underLine];
    }
}

- (void)setupTitleLabels {
    NSUInteger count = self.titleArray.count;
    
    // 添加所有的标题
    CGFloat labelW = 0;
    CGFloat labelH = self.ys_height;
    CGFloat labelX = 0;
    CGFloat labelY = 0;
    
    for (NSInteger i = 0; i < self.titleArray.count; i++) {
        // 1. 布局
        UILabel *titleLabel = [[YSDisplayTitleLabel alloc] init];
        titleLabel.text = self.titleArray[i];
        titleLabel.textColor = i == self.style.selectIndex ? self.style.titleSelectedColor : self.style.titleNormalColor;
        titleLabel.font = self.style.titleFont;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.tag = i;
        [self.scrollView addSubview:titleLabel];
        
        // 2. 计算位置
        CGRect titleBounds = [titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:titleLabel.font} context:nil];
        [self.titleSizeArray addObject:[NSValue valueWithCGSize:titleBounds.size]];
        
        if (self.style.isScrollEnable) {
            CGFloat width = self.style.titleWidth > 0 ? self.style.titleWidth : titleBounds.size.width;
            labelW = width + self.style.titleMargin;
            UILabel *lastLabel = self.titleLabelArray.lastObject;
            labelX = CGRectGetMaxX(lastLabel.frame);
        } else {
            labelW = self.ys_width / count;
            labelX = labelW * i;
        }
        titleLabel.frame = CGRectMake(labelX, labelY, labelW, labelH);
        [self.titleLabelArray addObject:titleLabel];
        
        // 3. 添加响应
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelClick:)];
        titleLabel.userInteractionEnabled = YES;
        [titleLabel addGestureRecognizer:tapGes];
    }
    
    // 设置标题滚动视图的内容范围
    UILabel *lastLabel = self.titleLabelArray.lastObject;
    self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(lastLabel.frame), 0);
    
    // 选中第 selectIndex 个
    UILabel *selectLabel = self.titleLabelArray[self.style.selectIndex];
    [self titleLabelClick: selectLabel.gestureRecognizers.firstObject];
}

#pragma mark -
#pragma mark Actions
- (void)titleLabelClick:(UITapGestureRecognizer *)tapGes {
    _isClickTitle = YES;
    
    // 1. 获取点击的label
    UILabel *label = (UILabel *)tapGes.view;
    
    // 2. 调整视图
    [self adjustTitleLabel:label];
    
    // 记录一下当前ContentView的偏移量
    self.lastOffsetX = self.currentIndex * self.ys_width;
    // 3. 通知ContentView进行调整
    [self.delegate titleView:self targetIndex:self.currentIndex];
    
    _isClickTitle = NO;
}

- (void)adjustTitleLabel:(UILabel *)label {
    for (YSDisplayTitleLabel *labelView in self.titleLabelArray) {
        if (label == labelView) { continue; }
        
        if (self.style.isShowTitleScale) {
            labelView.transform = CGAffineTransformIdentity;
        }
        
        labelView.textColor = self.style.titleNormalColor;
        
        if (self.style.isShowTitleGradient && self.style.titleColorGradientStyle == YSTitleColorGradientStyleFill) {
            labelView.fillColor = self.style.titleNormalColor;
            labelView.progress = 1;
        }
    }
    
    // 标题缩放
    if (self.style.isShowTitleScale) {
        label.transform = CGAffineTransformMakeScale(self.style.titleTransformScale, self.style.titleTransformScale);
    }
    
    // 修改标题选中颜色
    label.textColor = self.style.titleSelectedColor;
    
    // 设置标题居中
    if (self.style.isScrollEnable) {
        [self setLabelTitleCenter:label];
    }
    
    // 设置下标的位置
    if (self.style.isShowUnderLine) {
        [self setUpUnderLine:label];
    }
    
    // 设置遮罩
    if (self.style.isShowTitleCover && self.style.isScrollEnable) {
        [self setUpCoverView:label];
    }
    
    self.currentIndex = label.tag;
}

- (void)setLabelTitleCenter:(UILabel *)label {
    // 设置标题滚动区域的偏移量
    CGFloat offsetX = label.center.x - self.scrollView.ys_width * 0.5;
    
    if (offsetX < 0) {
        offsetX = 0;
    }
    
    // 计算下最大的标题视图滚动区域
    CGFloat maxOffsetX = self.scrollView.contentSize.width - self.scrollView.ys_width;
    
    if (maxOffsetX < 0) {
        maxOffsetX = 0;
    }
    
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    
    // 滚动区域
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

- (void)setUpUnderLine:(UILabel *)label {
    CGSize labelSize = [self.titleSizeArray[label.tag] CGSizeValue];
    
    // 最开始不需要动画
    if (self.underLine.ys_x == 0) {
        if (self.style.isUnderLineEqualTitleWidth) {
            self.underLine.ys_width = label.ys_width;
        } else {
            self.underLine.ys_width = labelSize.width;
        }
        
        self.underLine.ys_centerX = label.ys_centerX;
        return;
    }
    
    // 点击时候需要动画
    [UIView animateWithDuration:0.25 animations:^{
        if (self.style.isUnderLineEqualTitleWidth) {
            self.underLine.ys_width = label.ys_width;
        } else {
            self.underLine.ys_width = labelSize.width;
        }
        
        self.underLine.ys_centerX = label.ys_centerX;
    }];
    
    NSLog(@"%@", self.underLine);
    
}

- (void)setUpCoverView:(UILabel *)label {
    CGSize labelSize = [self.titleSizeArray[label.tag] CGSizeValue];
    CGFloat border = 5;
    CGFloat coverH = labelSize.height + 2 * border;
    CGFloat coverW = labelSize.width + 2 * border;
    
    self.coverView.ys_height = coverH;
    self.coverView.ys_centerY = self.scrollView.ys_height * 0.5;
    
    // 最开始不需要动画
    if (self.coverView.ys_x == 0) {
        self.coverView.ys_width = coverW;
        
        self.coverView.ys_centerX = label.ys_centerX;
        return;
    }
    
    // 点击时候需要动画
    [UIView animateWithDuration:0.25 animations:^{
        self.coverView.ys_width = coverW;
        
        self.coverView.ys_centerX = label.ys_centerX;
    }];
}

#pragma mark -
#pragma mark 懒加载
- (NSMutableArray *)titleLabelArray {
    if (!_titleLabelArray) {
        _titleLabelArray = [NSMutableArray array];
    }
    return _titleLabelArray;
}

- (NSMutableArray *)titleSizeArray {
    if (!_titleSizeArray) {
        _titleSizeArray = [NSMutableArray array];
    }
    return _titleSizeArray;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.scrollsToTop = NO;
        _scrollView.backgroundColor = self.style.titleBackgroundColor;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

- (UIView *)coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] init];
        _coverView.backgroundColor = self.style.coverColor;
        _coverView.layer.cornerRadius = self.style.coverCornerRadius;
    }
    return _coverView;
}

- (UIView *)underLine {
    if (!_underLine) {
        _underLine = [[UIView alloc] init];
        _underLine.backgroundColor = self.style.underLineColor;
        _underLine.ys_height = self.style.underLineHeight;
        _underLine.ys_y = self.ys_height - self.style.underLineHeight;
    }
    return _underLine;
}

- (UIView *)separatorLine {
    if (!_separatorLine) {
        _separatorLine = [[UIView alloc] init];
        _separatorLine.backgroundColor = self.style.titleSeparatorColor;
        _separatorLine.frame = CGRectMake(0, self.ys_height - .5, self.ys_width, .5);
    }
    return _underLine;
}

#pragma mark -
#pragma mark YSContentViewDelegate
- (void)contentView:(YSContentView *)contentView targetIndex:(NSInteger)targetIndex {
    [self adjustTitleLabel:self.titleLabelArray[targetIndex]];
}

- (void)contentView:(YSContentView *)contentView targetIndex:(NSInteger)targetIndex offsetX:(CGFloat)offsetX {
    // 左边按钮
    YSDisplayTitleLabel *leftLabel = self.titleLabelArray[targetIndex];
    
    // 右边角标
    NSInteger rightIndex = targetIndex + 1;
    
    // 右边按钮
    YSDisplayTitleLabel *rightLabel = nil;
    
    if (rightIndex < self.titleLabelArray.count) {
        rightLabel = self.titleLabelArray[rightIndex];
    }
    
    // 字体放大
    if (self.style.isShowTitleScale) {
        [self setUpTitleScaleWithOffset:offsetX rightLabel:rightLabel leftLabel:leftLabel];
    }
    
    // 设置下标偏移
    if (self.style.isShowUnderLine && self.style.isDelayScroll == NO) { // 延迟滚动，不需要移动下标
        [self setUpUnderLineOffset:offsetX rightLabel:rightLabel leftLabel:leftLabel];
    }
    
    // 设置遮盖偏移
    if (self.style.isShowTitleCover && self.style.isScrollEnable) {
        [self setUpCoverOffset:offsetX rightLabel:rightLabel leftLabel:leftLabel];
    }
    
    // 设置标题渐变
    if (self.style.isShowTitleGradient) {
        [self setUpTitleColorGradientWithOffset:offsetX rightLabel:rightLabel leftLabel:leftLabel];
    }
    
    // 记录上一次的偏移量
    self.lastOffsetX = offsetX;
}

#pragma mark -
#pragma mark Title效果
// 标题缩放
- (void)setUpTitleScaleWithOffset:(CGFloat)offsetX rightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel {
    // 获取右边缩放
    CGFloat rightSacle = offsetX / self.ys_width - leftLabel.tag;
    
    CGFloat leftScale = 1 - rightSacle;
    
    CGFloat scaleTransform = self.style.titleTransformScale;
    
    scaleTransform -= 1;
    
    // 缩放按钮
    leftLabel.transform = CGAffineTransformMakeScale(leftScale * scaleTransform + 1, leftScale * scaleTransform + 1);
    
    // 1 ~ 1.3
    rightLabel.transform = CGAffineTransformMakeScale(rightSacle * scaleTransform + 1, rightSacle * scaleTransform + 1);
}

// 获取两个标题按钮宽度差值
- (CGFloat)widthDeltaWithRightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel {
    if (!self.style.isScrollEnable) {
        return 0.f;
    }
    CGSize titleSizeR = [self.titleSizeArray[rightLabel.tag] CGSizeValue];
    CGSize titleSizeL = [self.titleSizeArray[leftLabel.tag] CGSizeValue];
    return titleSizeR.width - titleSizeL.width;
}

// 设置下标偏移
- (void)setUpUnderLineOffset:(CGFloat)offsetX rightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel {
    if (_isClickTitle) return;
    
    // 获取移动距离
    CGFloat offsetDelta = offsetX - _lastOffsetX;
    
    // 标题宽度差值
    CGFloat widthDelta = [self widthDeltaWithRightLabel:rightLabel leftLabel:leftLabel];
    if (self.style.titleWidth > 0 && self.style.isUnderLineEqualTitleWidth) {
        widthDelta = 0;
    }
    
    // 获取两个标题中心点距离
    CGFloat centerDelta = centerDelta = rightLabel.ys_x - leftLabel.ys_x;
    if (self.style.titleWidth > 0 && !self.style.isUnderLineEqualTitleWidth) {
        centerDelta -= widthDelta * 0.5;
    }
    
    // 计算当前下划线偏移量
    CGFloat underLineTransformX = offsetDelta * centerDelta / self.ys_width;
    
    // 宽度递增偏移量
    CGFloat underLineWidth = offsetDelta * widthDelta / self.ys_width;
    
    self.underLine.ys_width += underLineWidth;
    self.underLine.ys_x += underLineTransformX;
}

// 设置遮盖偏移
- (void)setUpCoverOffset:(CGFloat)offsetX rightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel {
    if (_isClickTitle) return;
    
    // 标题宽度差值
    CGFloat widthDelta = [self widthDeltaWithRightLabel:rightLabel leftLabel:leftLabel];
    
    // 获取两个标题中心点距离
    CGFloat centerDelta = rightLabel.ys_x - leftLabel.ys_x;
    if (self.style.titleWidth > 0) {
        centerDelta -= widthDelta * 0.5;
    }
    
    // 获取移动距离
    CGFloat offsetDelta = offsetX - _lastOffsetX;
    
    // 计算当前下划线偏移量
    CGFloat coverTransformX = offsetDelta * centerDelta / self.ys_width;
    
    // 宽度递增偏移量
    CGFloat coverWidth = offsetDelta * widthDelta / self.ys_width;
    
    self.coverView.ys_width += coverWidth;
    self.coverView.ys_x += coverTransformX;
    
}

// 设置标题颜色渐变
- (void)setUpTitleColorGradientWithOffset:(CGFloat)offsetX rightLabel:(YSDisplayTitleLabel *)rightLabel leftLabel:(YSDisplayTitleLabel *)leftLabel {
    if (self.style.isShowTitleGradient == NO) return;
    
    // 获取右边缩放
    CGFloat rightSacle = offsetX / self.ys_width - leftLabel.tag;
    
    // 获取左边缩放比例
    CGFloat leftScale = 1 - rightSacle;
    
    // RGB渐变
    if (self.style.titleColorGradientStyle == YSTitleColorGradientStyleRGB) {
        CGFloat r = _endR - _startR;
        CGFloat g = _endG - _startG;
        CGFloat b = _endB - _startB;
        
        // rightColor
        // 1 0 0
        UIColor *rightColor = [UIColor colorWithRed:_startR + r * rightSacle green:_startG + g * rightSacle blue:_startB + b * rightSacle alpha:1];
        
        // 0.3 0 0
        // 1 -> 0.3
        // leftColor
        UIColor *leftColor = [UIColor colorWithRed:_startR +  r * leftScale  green:_startG +  g * leftScale  blue:_startB +  b * leftScale alpha:1];
        
        // 右边颜色
        rightLabel.textColor = rightColor;
        
        // 左边颜色
        leftLabel.textColor = leftColor;
        return;
    }
    
    // 填充渐变
    if (self.style.titleColorGradientStyle == YSTitleColorGradientStyleFill) {
        
        // 获取移动距离
        CGFloat offsetDelta = offsetX - _lastOffsetX;
        
        if (offsetDelta > 0) { // 往右边
            rightLabel.textColor = self.style.titleNormalColor;
            rightLabel.fillColor = self.style.titleSelectedColor;
            rightLabel.progress = rightSacle;
            
            leftLabel.textColor = self.style.titleSelectedColor;
            leftLabel.fillColor = self.style.titleNormalColor;
            leftLabel.progress = rightSacle;
            
        } else if(offsetDelta < 0){ // 往左边
            
            rightLabel.textColor = self.style.titleNormalColor;
            rightLabel.fillColor = self.style.titleSelectedColor;
            rightLabel.progress = rightSacle;
            
            leftLabel.textColor = self.style.titleSelectedColor;
            leftLabel.fillColor = self.style.titleNormalColor;
            leftLabel.progress = rightSacle;
            
        }
    }
}

@end


@implementation YSDisplayTitleLabel

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    [_fillColor set];
    rect.size.width = rect.size.width * _progress;
    UIRectFillUsingBlendMode(rect, kCGBlendModeSourceIn);
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES;
        self.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

- (void)setProgress:(CGFloat)progress {
    _progress = progress;
    
    [self setNeedsDisplay];
}

@end
